// 切换标签页
function switchTab(tabType) {
    // 隐藏所有内容
    document.getElementById('performance-content').classList.add('hidden');
    document.getElementById('payment-content').classList.add('hidden');
    document.getElementById('project-content').classList.add('hidden');
    
    // 移除所有标签的活跃状态和内联样式类
    document.getElementById('performance-tab').classList.remove('tab-active', 'text-primary', 'border-b-2', 'border-primary');
    document.getElementById('performance-tab').classList.add('text-neutral-500');
    document.getElementById('payment-tab').classList.remove('tab-active', 'text-primary', 'border-b-2', 'border-primary');
    document.getElementById('payment-tab').classList.add('text-neutral-500');
    document.getElementById('project-tab').classList.remove('tab-active', 'text-primary', 'border-b-2', 'border-primary');
    document.getElementById('project-tab').classList.add('text-neutral-500');
    
    // 显示选中的内容和激活对应的标签
    if (tabType === 'performance') {
        document.getElementById('performance-content').classList.remove('hidden');
        document.getElementById('performance-tab').classList.add('tab-active', 'text-primary', 'border-b-2', 'border-primary');
        document.getElementById('performance-tab').classList.remove('text-neutral-500');
        
        // 确保人天投入图表正确渲染
        if (window.performanceChart) {
            window.performanceChart.resize();
        }
    } else if (tabType === 'payment') {
        document.getElementById('payment-content').classList.remove('hidden');
        document.getElementById('payment-tab').classList.add('tab-active', 'text-primary', 'border-b-2', 'border-primary');
        document.getElementById('payment-tab').classList.remove('text-neutral-500');
        
        // 确保绩效考核图表在标签页切换时正确渲染
        if (window.paymentChart) {
            window.paymentChart.resize();
        }
    } else if (tabType === 'project') {
        document.getElementById('project-content').classList.remove('hidden');
        document.getElementById('project-tab').classList.add('tab-active', 'text-primary', 'border-b-2', 'border-primary');
        document.getElementById('project-tab').classList.remove('text-neutral-500');
        
        // 确保项目投入分析图表正确渲染
        if (window.projectChart) {
            window.projectChart.resize();
        }
    }
}

// 初始化部门卡片点击事件
function initRegionCards() {
    const detailButtons = document.querySelectorAll('.text-primary');
    const backButton = document.getElementById('back-button');
    const regionBackButton = document.getElementById('region-back-button');
    
    detailButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            // 找到对应的部门名称
            const regionName = this.closest('.card-shadow').querySelector('h3').textContent;
            
            // 显示部门员工详情页
            showRegionDetail(regionName);
        });
    });
    
    // 返回首页按钮事件
    if (backButton) {
        // 保留原有逻辑，这里backButton已经有onclick属性设置为跳转到index.html
    }
    
    // 部门详情返回按钮事件
    if (regionBackButton) {
        regionBackButton.addEventListener('click', function() {
            // 隐藏部门员工详情页
            document.getElementById('region-detail-content').classList.add('hidden');
        });
    }
}

// 显示部门员工详情
function showRegionDetail(regionName) {
    // 显示部门员工详情页
    document.getElementById('region-detail-content').classList.remove('hidden');
    
    // 更新页面标题
    document.getElementById('region-detail-title').textContent = regionName + '员工详情';
    
    // 获取人员列表容器
    const salespersonList = document.getElementById('salesperson-list');
    
    // 清空列表
    salespersonList.innerHTML = '';
    
    // 获取该部门的员工数据
    const salespersons = window.regionSalespersonData[regionName] || [];
    
    // 如果没有数据，显示提示信息
    if (salespersons.length === 0) {
        salespersonList.innerHTML = '<div class="bg-white rounded-lg p-4 card-shadow text-center text-neutral-500">暂无员工数据</div>';
        return;
    }
    
    // 生成员工卡片
    salespersons.forEach(salesperson => {
        const progressPercent = (salesperson.salesProgress.current / salesperson.salesProgress.target * 100).toFixed(1);
        
        const card = document.createElement('div');
        card.className = 'bg-white rounded-lg overflow-hidden card-shadow';
        card.innerHTML = `
            <div class="p-4">
                <!-- 上方：头像、姓名、职位 -->
                <div class="flex items-center space-x-4 mb-4 pb-4 border-b border-neutral-100">
                    <div class="w-10 h-10 rounded-full bg-neutral-100 flex items-center justify-center">
                        <i class="fa fa-id-card-o text-neutral-400"></i>
                    </div>
                    <div>
                        <h4 class="font-semibold text-base">${salesperson.name}</h4>
                        <p class="text-sm text-neutral-500">${salesperson.position}</p>
                    </div>
                </div>
                
                <!-- 下方：其他信息 -->
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">绩效考核得分</p>
                        <p class="font-semibold text-lg ${getRateColorClass(salesperson.monthlyAchievementRate)}">${salesperson.monthlyAchievementRate}</p>
                    </div>
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">季度排名</p>
                        <p class="font-semibold text-lg">${salesperson.paymentRate}</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">项目参与率</p>
                        <p class="font-semibold text-lg ${getRateColorClass(salesperson.salesProgress.current)}">${progressPercent}%</p>
                    </div>
                    <div class="text-right">
                        <button class="text-primary text-sm font-medium flex items-center justify-end space-x-1 hover:underline">
                            <span>查看详情</span>
                            <i class="fa fa-angle-right"></i>
                        </button>
                    </div>
                </div>
                
                <div class="mt-2">
                    <div class="flex justify-between text-xs mb-1">
                        <span class="text-neutral-500">个人目标完成度</span>
                        <span class="text-neutral-600">¥${formatNumber(salesperson.salesProgress.current)}/${formatNumber(salesperson.salesProgress.target)}</span>
                    </div>
                    <div class="w-full bg-neutral-100 rounded-full h-2.5">
                        <div class="bg-primary h-2.5 rounded-full" style="width: ${progressPercent}%" id="progress-bar"></div>
                    </div>
                </div>
            </div>
        `;
        
        salespersonList.appendChild(card);
    });
}

// 初始化人天投入排行榜图表
function initPerformanceRankingChart() {
    try {
        // 获取canvas元素
        const canvas = document.getElementById('performanceRankingChart');
        if (!canvas) {
            console.error('无法找到canvas元素: performanceRankingChart');
            return;
        }
        
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取canvas上下文');
            return;
        }
        
        // 调用更新图表函数
        updatePerformanceChart();
        
        console.log('人天投入排行榜图表已成功初始化');
    } catch (error) {
        console.error('初始化人天投入排行榜时出错:', error);
    }
}

// 更新人天投入图表数据的函数
function updatePerformanceChart() {
    // 获取当前选中的年份
    const yearFilter = document.getElementById('yearFilter');
    const year = yearFilter ? yearFilter.value : '2025';
    
    // 按年份获取部门人天投入数据（包含四个季度）
    const departmentData = getDepartmentManDaysByYearAndQuarter(year);
    
    // 获取部门列表
    const departments = Object.keys(departmentData);
    
    // 准备四个季度的数据
    const quarter1Data = departments.map(dept => departmentData[dept].quarter1);
    const quarter2Data = departments.map(dept => departmentData[dept].quarter2);
    const quarter3Data = departments.map(dept => departmentData[dept].quarter3);
    const quarter4Data = departments.map(dept => departmentData[dept].quarter4);
    
    // 计算每个部门的总人天，用于排序
    const totalManDays = departments.map(dept => 
        departmentData[dept].quarter1 + 
        departmentData[dept].quarter2 + 
        departmentData[dept].quarter3 + 
        departmentData[dept].quarter4
    );
    
    // 根据总人天排序部门
    const sortedDepartments = departments
        .map((dept, index) => ({ dept, total: totalManDays[index] }))
        .sort((a, b) => b.total - a.total)
        .map(item => item.dept);
    
    // 重新排序各季度数据
    const sortedQuarter1Data = sortedDepartments.map(dept => departmentData[dept].quarter1);
    const sortedQuarter2Data = sortedDepartments.map(dept => departmentData[dept].quarter2);
    const sortedQuarter3Data = sortedDepartments.map(dept => departmentData[dept].quarter3);
    const sortedQuarter4Data = sortedDepartments.map(dept => departmentData[dept].quarter4);
    
    // 获取最大值并设置x轴最大值
    const maxTotal = Math.max(...totalManDays);
    const xAxisMax = Math.ceil(maxTotal * 1.1); // 设置为最大值的110%，留出显示空间
    
    // 如果图表已存在，销毁它
    if (window.performanceChart) {
        window.performanceChart.destroy();
    }
    
    // 获取canvas元素和上下文
    const canvas = document.getElementById('performanceRankingChart');
    const ctx = canvas.getContext('2d');
    
    // 创建新图表 - 横向堆叠柱状图
    window.performanceChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedDepartments,
            datasets: [
                {
                    label: '第一季度',
                    data: sortedQuarter1Data,
                    backgroundColor: 'rgba(54, 162, 235, 0.7)', // 蓝色
                    borderWidth: 0,
                    borderRadius: 4,
                },
                {
                    label: '第二季度',
                    data: sortedQuarter2Data,
                    backgroundColor: 'rgba(75, 192, 192, 0.7)', // 青绿色
                    borderWidth: 0,
                    borderRadius: 4,
                },
                {
                    label: '第三季度',
                    data: sortedQuarter3Data,
                    backgroundColor: 'rgba(255, 206, 86, 0.7)', // 黄色
                    borderWidth: 0,
                    borderRadius: 4,
                },
                {
                    label: '第四季度',
                    data: sortedQuarter4Data,
                    backgroundColor: 'rgba(255, 99, 132, 0.7)', // 红色
                    borderWidth: 0,
                    borderRadius: 4,
                }
            ]
        },
        // 明确指定要使用的插件
        plugins: [ChartDataLabels],
        options: {
            indexAxis: 'y', // 设置为横向柱状图
            // 调整布局边距，为右侧标签留出更多空间
            layout: {
                padding: { right: 40 }
            },
            // 启用堆叠模式
            scales: {
                x: {
                    stacked: true, // 堆叠
                    display: true, // 显示x轴
                    beginAtZero: true,
                    max: xAxisMax,
                    grid: {
                        display: true,
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return value + '人天';
                        }
                    }
                },
                y: {
                    stacked: true, // 堆叠
                    grid: {
                        display: false
                    }
                }
            },
            // 修改点击事件处理
            onClick: function(event, elements) {
                if (elements.length > 0) {
                    const elementIndex = elements[0].index;
                    const deptName = sortedDepartments[elementIndex];
                    // 直接在人天投入页签内定位
                    scrollToRegionCard(deptName, 'performance');
                }
            },
            plugins: {
                // 显示图例，标明各季度颜色
                legend: {
                    display: true,
                    position: 'top',
                    labels: {
                        boxWidth: 12,
                        usePointStyle: true,
                        pointStyle: 'circle',
                        font: {
                            size: 10 // 减小字体大小，默认为12
                        },
                        padding: 8 // 调整图例项之间的间距
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.dataset.label || '';
                            const value = context.raw || 0;
                            return `${label}: ${value}人天`;
                        },
                        footer: function(tooltipItems) {
                            // 显示总人天
                            let total = 0;
                            tooltipItems.forEach(item => {
                                total += item.raw;
                            });
                            return `总计: ${total}人天`;
                        }
                    }
                },
                // 数据标签插件配置
                datalabels: {
                    display: true,
                    anchor: 'center',
                    align: 'center',
                    formatter: function(value) {
                        // 只在值大于30时显示标签，避免标签拥挤
                        return value > 30 ? value : '';
                    },
                    color: '#333',
                    font: {
                        weight: 'bold',
                        size: 10
                    },
                    clip: false
                }
            },
            animation: {
                duration: 1500,
                easing: 'easeOutQuart'
            },
            maintainAspectRatio: false
        }
    });
}

// 根据年份和季度获取部门人天投入数据的函数（模拟数据）
function getDepartmentManDaysByYearAndQuarter(year) {
    // 限定只包含研发部、实施部、技术部
    // 根据不同年份返回四个季度的数据
    const departments = ['研发部', '实施部', '技术部'];
    const data = {};
    
    const yearFactor = parseInt(year) - 2023;
    
    departments.forEach(dept => {
        // 为每个部门生成四个季度的模拟数据
        data[dept] = {
            quarter1: 0,
            quarter2: 0,
            quarter3: 0,
            quarter4: 0
        };
        
        // 根据部门类型设置基础值
        let baseValue = 0;
        if (dept === '研发部') baseValue = 800 + (yearFactor * 100);
        else if (dept === '实施部') baseValue = 600 + (yearFactor * 80);
        else if (dept === '技术部') baseValue = 400 + (yearFactor * 60);
        
        // 生成四个季度的数据，每个季度有一定波动
        data[dept].quarter1 = Math.round(baseValue * (0.9 + Math.random() * 0.2));
        data[dept].quarter2 = Math.round(baseValue * (0.85 + Math.random() * 0.2));
        data[dept].quarter3 = Math.round(baseValue * (0.95 + Math.random() * 0.2));
        data[dept].quarter4 = Math.round(baseValue * (1.0 + Math.random() * 0.2));
    });
    
    return data;
}

// 修改initPaymentRankingChart函数，改为员工绩效考核图表
function initPaymentRankingChart() {
    try {
        // 获取canvas元素
        const canvas = document.getElementById('paymentRankingChart');
        if (!canvas) {
            console.error('无法找到canvas元素: paymentRankingChart');
            return;
        }
        
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取canvas上下文');
            return;
        }
        
        // 从所有部门中收集员工数据
        let allEmployees = [];
        for (const dept in window.regionSalespersonData) {
            if (window.regionSalespersonData.hasOwnProperty(dept)) {
                const employees = window.regionSalespersonData[dept];
                employees.forEach(emp => {
                    allEmployees.push({
                        name: emp.name,
                        department: dept,
                        position: emp.position,
                        scores: emp.performanceScores
                    });
                });
            }
        }
        
        // 计算员工近四个季度的平均分数
        allEmployees.forEach(emp => {
            const scores = emp.scores;
            const total = scores.quarter1 + scores.quarter2 + scores.quarter3 + scores.quarter4;
            emp.averageScore = (total / 4).toFixed(1);
        });
        
        // 根据平均分数排序
        allEmployees.sort((a, b) => b.averageScore - a.averageScore);
        
        // 只显示前10名员工
        const topEmployees = allEmployees.slice(0, 10);
        
        // 提取排序后的数据
        const employeeLabels = topEmployees.map(emp => `${emp.name} (${emp.department})`);
        const quarter1Scores = topEmployees.map(emp => emp.scores.quarter1);
        const quarter2Scores = topEmployees.map(emp => emp.scores.quarter2);
        const quarter3Scores = topEmployees.map(emp => emp.scores.quarter3);
        const quarter4Scores = topEmployees.map(emp => emp.scores.quarter4);
        
        // 创建图表 - 员工绩效考核近四个季度对比
        window.paymentChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: employeeLabels,
                datasets: [
                    {
                        label: '第1季度',
                        data: quarter1Scores,
                        backgroundColor: 'rgba(54, 162, 235, 0.7)',
                        borderWidth: 0,
                        borderRadius: 4,
                    },
                    {
                        label: '第2季度',
                        data: quarter2Scores,
                        backgroundColor: 'rgba(75, 192, 192, 0.7)',
                        borderWidth: 0,
                        borderRadius: 4,
                    },
                    {
                        label: '第3季度',
                        data: quarter3Scores,
                        backgroundColor: 'rgba(153, 102, 255, 0.7)',
                        borderWidth: 0,
                        borderRadius: 4,
                    },
                    {
                        label: '第4季度',
                        data: quarter4Scores,
                        backgroundColor: 'rgba(255, 159, 64, 0.7)',
                        borderWidth: 0,
                        borderRadius: 4,
                    }
                ]
            },
            // 明确指定要使用的插件
            plugins: [ChartDataLabels],
            options: {
                indexAxis: 'y', // 设置为横向柱状图
                // 调整布局边距，为右侧标签留出更多空间
                layout: {
                    padding: {
                        right: 40 // 增加右侧内边距
                    }
                },
                // 修改点击事件处理 - 移除页签切换，直接在当前页签定位
                onClick: function(event, elements) {
                    if (elements.length > 0) {
                        const elementIndex = elements[0].index;
                        const employeeData = topEmployees[elementIndex];
                        // 直接在绩效考核页签内定位员工所属部门卡片
                        scrollToRegionCard(employeeData.department, 'payment');
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top',
                        labels: {
                            boxWidth: 12,
                            usePointStyle: true,
                            pointStyle: 'circle',
                            font: {
                                size: 10
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.dataset.label}: ${context.raw}`;
                            }
                        }
                    },
                    // 增强数据标签配置
                    datalabels: {
                        display: true,
                        anchor: 'end',
                        align: 'right',
                        formatter: function(value) {
                            return value;
                        },
                        color: '#333',
                        font: {
                            weight: 'bold',
                            size: 10
                        },
                        // 确保标签不会被裁剪
                        clip: false
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        max: 100
                    },
                    y: {
                        grid: {
                            display: false
                        }
                    }
                },
                animation: {
                    duration: 1500,
                    easing: 'easeOutQuart'
                },
                maintainAspectRatio: false
            }
        });
        
        console.log('员工绩效考核排行榜图表已成功初始化');
    } catch (error) {
        console.error('初始化员工绩效考核排行榜图表时出错:', error);
    }
}

// 初始化项目投入分析图表
function initProjectRankingChart() {
    try {
        // 获取canvas元素
        const canvas = document.getElementById('projectRankingChart');
        if (!canvas) {
            console.error('无法找到canvas元素: projectRankingChart');
            return;
        }
        
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取canvas上下文');
            return;
        }
        
        // 获取选中的年份
        const yearSelect = document.getElementById('projectYearFilter');
        const selectedYear = yearSelect ? yearSelect.value : '2025';
        
        // 获取项目数据
        const projectData = getProjectData(selectedYear);
        
        // 按已投入人天排序
        const sortedProjects = projectData.sort((a, b) => b.actualManDays - a.actualManDays);
        
        // 只显示前10个项目
        const topProjects = sortedProjects.slice(0, 10);
        
        // 提取数据
        const projectNames = topProjects.map(project => project.name);
        const plannedManDays = topProjects.map(project => project.plannedManDays);
        const actualManDays = topProjects.map(project => project.actualManDays);
        
        // 创建图表
        window.projectChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: projectNames,
                datasets: [
                    {
                        label: '计划投入人天',
                        data: plannedManDays,
                        backgroundColor: 'rgba(200, 200, 200, 0.7)',
                        borderWidth: 0,
                        borderRadius: 4,
                    },
                    {
                        label: '已投入人天',
                        data: actualManDays,
                        backgroundColor: 'rgba(54, 162, 235, 0.7)',
                        borderWidth: 0,
                        borderRadius: 4,
                    }
                ]
            },
            plugins: [ChartDataLabels],
            options: {
                indexAxis: 'y', // 设置为横向柱状图
                layout: {
                    padding: {
                        right: 40
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top',
                        labels: {
                            boxWidth: 12,
                            usePointStyle: true,
                            pointStyle: 'circle',
                            font: {
                                size: 10
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.dataset.label}: ${context.raw}`;
                            }
                        }
                    },
                    datalabels: {
                        display: true,
                        anchor: 'end',
                        align: 'right',
                        formatter: function(value) {
                            return value;
                        },
                        color: '#333',
                        font: {
                            weight: 'bold',
                            size: 10
                        },
                        clip: false
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            display: true,
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        }
                    }
                },
                animation: {
                    duration: 1500,
                    easing: 'easeOutQuart'
                },
                maintainAspectRatio: false
            }
        });
        
        console.log('项目投入排行榜图表已成功初始化');
        
        // 生成项目卡片
        generateProjectCards(projectData);
    } catch (error) {
        console.error('初始化项目投入排行榜图表时出错:', error);
    }
}

// 获取项目数据（模拟数据）
function getProjectData(year) {
    // 根据年份生成不同的模拟项目数据
    const projects = [
        {
            id: 'PROJ-001',
            name: '企业资源管理系统升级',
            manager: '张明',
            members: ['张明', '李强', '王芳', '赵伟', '陈静'],
            amount: 1800000,
            plannedManDays: 1200,
            actualManDays: 1150,
            progress: 95
        },
        {
            id: 'PROJ-002',
            name: '移动应用开发项目',
            manager: '李强',
            members: ['李强', '刘思', '张伟', '黄娜'],
            amount: 1200000,
            plannedManDays: 800,
            actualManDays: 850,
            progress: 100
        },
        {
            id: 'PROJ-003',
            name: '客户关系管理系统建设',
            manager: '王芳',
            members: ['王芳', '张明', '刘思', '赵伟', '陈静', '黄娜'],
            amount: 2500000,
            plannedManDays: 1500,
            actualManDays: 1320,
            progress: 88
        },
        {
            id: 'PROJ-004',
            name: '数据分析平台搭建',
            manager: '赵伟',
            members: ['赵伟', '陈静', '张伟'],
            amount: 900000,
            plannedManDays: 600,
            actualManDays: 580,
            progress: 97
        },
        {
            id: 'PROJ-005',
            name: '云服务迁移项目',
            manager: '陈静',
            members: ['陈静', '李强', '黄娜', '刘思'],
            amount: 1600000,
            plannedManDays: 1000,
            actualManDays: 950,
            progress: 95
        }
    ];
    
    // 根据年份调整数据，增加一些变化
    const yearFactor = parseInt(year) - 2025;
    return projects.map(project => ({
        ...project,
        actualManDays: Math.round(project.actualManDays * (1 + yearFactor * 0.05)),
        amount: Math.round(project.amount * (1 + yearFactor * 0.08))
    }));
}

// 生成项目卡片
function generateProjectCards(projects) {
    const container = document.getElementById('projectCardsContainer');
    if (!container) {
        console.error('无法找到项目卡片容器');
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 生成每个项目的卡片
    projects.forEach(project => {
        const completionRate = (project.actualManDays / project.plannedManDays * 100).toFixed(1);
        const card = document.createElement('div');
        card.className = 'bg-white rounded-lg overflow-hidden card-shadow';
        card.innerHTML = `
            <div class="p-4 border-b border-neutral-100">
                <h3 class="text-base font-medium text-neutral-800">${project.name}</h3>
                <p class="text-xs text-neutral-500 mt-1">${project.id}</p>
            </div>
            <div class="p-4">
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">项目负责人</p>
                        <p class="font-medium">${project.manager}</p>
                    </div>
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">项目成员</p>
                        <p class="font-medium text-sm">${project.members.join('、')}</p>
                    </div>
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">项目金额</p>
                        <p class="font-semibold text-lg">¥${formatNumber(project.amount)}</p>
                    </div>
                    <div>
                        <p class="text-xs text-neutral-500 mb-1">完成进度</p>
                        <p class="font-semibold text-lg">${project.progress}%</p>
                    </div>
                </div>
                <div>
                    <div class="flex justify-between text-xs mb-1">
                        <span class="text-neutral-500">人天投入情况</span>
                        <span class="text-neutral-600">${project.actualManDays}/${project.plannedManDays}人天 (${completionRate}%)</span>
                    </div>
                    <div class="w-full bg-neutral-100 rounded-full h-2.5">
                        <div class="bg-blue-400 h-2.5 rounded-full" style="width: ${completionRate}%"></div>
                    </div>
                </div>
            </div>
        `;
        container.appendChild(card);
    });
}

// 格式化数字，添加千分位分隔符
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// 根据达成率获取颜色类
function getRateColorClass(rate) {
    if (rate >= 90) return 'text-success';
    if (rate >= 70) return 'text-primary';
    return 'text-danger';
}

// 修改滚动到区域卡片的函数，支持在指定页签内查找
function scrollToRegionCard(regionName, tabType) {
    // 移除区域名称中可能存在的特殊字符，确保准确匹配
    const normalizedRegionName = regionName.trim();
    
    // 获取当前应该查找卡片的内容区域
    let contentAreaId = 'payment-content'; // 默认绩效考核内容
    if (tabType === 'performance') {
        contentAreaId = 'performance-content'; // 人天投入内容
    }
    
    // 获取对应的内容区域
    const contentArea = document.getElementById(contentAreaId);
    if (!contentArea) {
        console.error(`未找到内容区域: ${contentAreaId}`);
        return;
    }
    
    // 仅在指定的内容区域内查找卡片
    const allCards = contentArea.querySelectorAll('.card-shadow');
    let targetCard = null;
    
    allCards.forEach(card => {
        const regionTitle = card.querySelector('h3');
        if (regionTitle && regionTitle.textContent.trim() === normalizedRegionName) {
            targetCard = card;
        }
    });
    
    // 如果找到目标卡片，则滚动到该卡片
    if (targetCard) {
        console.log(`已在${tabType === 'performance' ? '人天投入' : '绩效考核'}页签找到部门卡片: ${regionName}`);
        // 添加高亮效果
        targetCard.classList.add('bg-blue-50');
        
        // 滚动到卡片位置
        targetCard.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
        
        // 3秒后移除高亮效果
        setTimeout(() => {
            targetCard.classList.remove('bg-blue-50');
        }, 3000);
    } else {
        console.log(`在${tabType === 'performance' ? '人天投入' : '绩效考核'}页签未找到部门卡片: ${regionName}`);
    }
}

// 部门员工数据 - 模拟数据
// 使用window对象作为命名空间
window.regionSalespersonData = {
    '研发部门': [
        {
            name: '王军',
            position: '高级工程师',
            personalTarget: 200000,
            monthlyAchievementRate: 92,
            paymentRate: '5/32',
            salesProgress: { current: 85, target: 100 },
            performanceScores: {
                quarter1: 92,
                quarter2: 88,
                quarter3: 95,
                quarter4: 90
            }
        },
        {
            name: '王明',
            position: '技术专家',
            personalTarget: 250000,
            monthlyAchievementRate: 88,
            paymentRate: '8/32',
            salesProgress: { current: 92, target: 100 },
            performanceScores: {
                quarter1: 85,
                quarter2: 90,
                quarter3: 88,
                quarter4: 92
            }
        },
        {
            name: '陈敏',
            position: '研发经理',
            personalTarget: 300000,
            monthlyAchievementRate: 95,
            paymentRate: '2/32',
            salesProgress: { current: 98, target: 100 },
            performanceScores: {
                quarter1: 96,
                quarter2: 94,
                quarter3: 97,
                quarter4: 95
            }
        }
    ],
    '市场部门': [
        {
            name: '李强',
            position: '市场专员',
            personalTarget: 150000,
            monthlyAchievementRate: 85,
            paymentRate: '12/25',
            salesProgress: { current: 88, target: 100 },
            performanceScores: {
                quarter1: 88,
                quarter2: 86,
                quarter3: 90,
                quarter4: 87
            }
        },
        {
            name: '张伟',
            position: '市场经理',
            personalTarget: 220000,
            monthlyAchievementRate: 90,
            paymentRate: '6/25',
            salesProgress: { current: 94, target: 100 },
            performanceScores: {
                quarter1: 91,
                quarter2: 93,
                quarter3: 89,
                quarter4: 92
            }
        }
    ],
    '销售部门': [
        {
            name: '张明',
            position: '销售代表',
            personalTarget: 180000,
            monthlyAchievementRate: 82,
            paymentRate: '15/28',
            salesProgress: { current: 85, target: 100 },
            performanceScores: {
                quarter1: 84,
                quarter2: 83,
                quarter3: 86,
                quarter4: 85
            }
        },
        {
            name: '赵丽',
            position: '销售经理',
            personalTarget: 240000,
            monthlyAchievementRate: 88,
            paymentRate: '8/28',
            salesProgress: { current: 91, target: 100 },
            performanceScores: {
                quarter1: 90,
                quarter2: 88,
                quarter3: 92,
                quarter4: 91
            }
        }
    ]
};

// 响应式处理
function handleResize() {
    const windowWidth = window.innerWidth;
    
    // 针对不同屏幕宽度的特殊处理
    if (windowWidth < 640) {
        // 移动端特殊处理
        console.log('移动端视图');
    } else {
        // 平板/桌面端特殊处理
        console.log('桌面端视图');
    }
    
    // 确保图表在窗口大小变化时正确调整
    if (window.paymentChart) {
        window.paymentChart.resize();
    }
    
    // 确保人天投入图表也能正确调整
    if (window.performanceChart) {
        window.performanceChart.resize();
    }
}

// 添加窗口大小变化监听
window.addEventListener('resize', handleResize);
// 初始调用一次
handleResize();

// 页面加载完成后初始化
window.addEventListener('load', function() {
    // 设置年份选择器默认值为当前年份
    const currentYear = new Date().getFullYear();
    
    // 初始化人天投入年份选择器
    const yearSelect = document.getElementById('yearFilter');
    if (yearSelect) {
        // 检查当前年份选项是否存在，如果不存在则添加
        let optionExists = false;
        for (let i = 0; i < yearSelect.options.length; i++) {
            if (yearSelect.options[i].value == currentYear) {
                optionExists = true;
                yearSelect.selectedIndex = i;
                break;
            }
        }
        
        if (!optionExists) {
            const newOption = document.createElement('option');
            newOption.value = currentYear;
            newOption.text = `${currentYear}年`;
            newOption.selected = true;
            yearSelect.appendChild(newOption);
        }
        
        // 为年份选择框添加change事件监听器
        yearSelect.addEventListener('change', updatePerformanceChart);
    }
    
    // 初始化绩效考核年份选择器
    const paymentYearSelect = document.getElementById('paymentYearFilter');
    if (paymentYearSelect) {
        // 检查当前年份选项是否存在，如果不存在则添加
        let optionExists = false;
        for (let i = 0; i < paymentYearSelect.options.length; i++) {
            if (paymentYearSelect.options[i].value == currentYear) {
                optionExists = true;
                paymentYearSelect.selectedIndex = i;
                break;
            }
        }
        
        if (!optionExists) {
            const newOption = document.createElement('option');
            newOption.value = currentYear;
            newOption.text = `${currentYear}年`;
            newOption.selected = true;
            paymentYearSelect.appendChild(newOption);
        }
        
        // 为年份选择框添加change事件监听器
        paymentYearSelect.addEventListener('change', function() {
            // 重新初始化绩效考核图表
            if (window.paymentChart) {
                window.paymentChart.destroy();
            }
            initPaymentRankingChart();
        });
    }
    
    // 初始化项目投入分析年份选择器
    const projectYearSelect = document.getElementById('projectYearFilter');
    if (projectYearSelect) {
        // 检查当前年份选项是否存在，如果不存在则添加
        let optionExists = false;
        for (let i = 0; i < projectYearSelect.options.length; i++) {
            if (projectYearSelect.options[i].value == currentYear) {
                optionExists = true;
                projectYearSelect.selectedIndex = i;
                break;
            }
        }
        
        if (!optionExists) {
            const newOption = document.createElement('option');
            newOption.value = currentYear;
            newOption.text = `${currentYear}年`;
            newOption.selected = true;
            projectYearSelect.appendChild(newOption);
        }
        
        // 为年份选择框添加change事件监听器
        projectYearSelect.addEventListener('change', function() {
            // 重新初始化项目投入分析图表
            if (window.projectChart) {
                window.projectChart.destroy();
            }
            initProjectRankingChart();
        });
    }
    
    // 初始化部门卡片点击事件
    initRegionCards();

    // 初始化人天投入排行榜图表
    initPerformanceRankingChart();
    
    // 初始化绩效考核排行榜图表
    initPaymentRankingChart();
    
    // 初始化项目投入分析图表
    initProjectRankingChart();
});